import {asyncRoutes} from '@/router/index'
import deepcopy from "deepcopy";

/**
 * 格式化路由
 * @param payload Array
 * @returns {{routes, authList}}
 */
export function genRoutes(payload) {
    const formatMenuTree = (list) => {
        return list.filter(father => {
            const childArr = list.filter(child => father.id === child.parentId)
            if (childArr.length > 0) {
                father.children = childArr
            }
            return father.type === 1 || father.type === 0
        })
    }
    // 格式化成树状菜单 做按钮权限用
    const formatMenu = formatMenuTree(payload)
    // 过滤路由
    const filterRoute = (routesMap) => {
        let res = []
        routesMap.forEach(routes => {
            if (routes.children && routes.children.length) {
                routes.children = filterRoute(routes.children)
            }
            // 后台webUrl匹配前端路由name
            const isRenderRoutes = formatMenu.find(item => {
                return item.webUrl === routes.name
            })
            if (isRenderRoutes) {
                res.push({
                    ...routes,
                    meta: {
                        title:isRenderRoutes.name,
                        sortNum: isRenderRoutes.orderNum,
                        icon: isRenderRoutes.icon
                    },
                })
            } else if (routes.path === '/') {
                res.push(routes)
            }
        })
        return res
    }
    const route = filterRoute(deepcopy(asyncRoutes))
    console.log(route)
    // 过滤所有页面按钮权限数组
    return {
        permission: formatMenu,
        route: route
    }
}
